package com.czh.job;

import com.czh.domain.entity.Article;
import com.czh.service.ArticleService;
import com.czh.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

// 定时文章浏览量同步回数据库
@Component
@EnableScheduling
@Slf4j
public class UpdateViewCountJob {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ArticleService articleService;
    @Scheduled(cron = "0/30 * * * * ?")
    public void updateViewCount(){
        Map<String, Object> map = redisCache.getCacheMap("article:viewCount");
        List<Article> collect = map.entrySet().stream().map(entry ->
                        new Article().setId(Long.parseLong(entry.getKey())).setViewCount(((Integer)entry.getValue()).longValue())).
                collect(Collectors.toList());
        log.info("更新浏览量"+map);
        articleService.updateBatchById(collect);
    }
}
